﻿

import Request from "../../base/request.js?t=202511041006"
import Storage from "../../base/storage.js?t=202511041006"
import { imageBaseUrl, isImageFile, downloadfun, dealTime, IgetDeptList, queryURLParams, IDeletePPEFile, getBrowserInfo } from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {

    const generateh = (text, isShort) => {
        if (isShort) {
            return h('div', {
                style: "width:100px;overflow:hidden;white-space: nowrap;text-overflow: ellipsis; -o-text-overflow: ellipsis;cursor:pointer"
            }, { default: () => text })
        } else {
            return h('div', {
                style: "width:300px;height:auto;"
            }, { default: () => text })
        }

    }

    const data = reactive({
        pdfOpen: false,
        pdfurl: "",

        messageTest: "",
        proxy: "",
        cIndex: 2,
        uploadLock:false,
        cid:"",
        deptList:[],
        tabList: [],
        areaList: [
            { label: '浦东', value: 1 },
            { label: '大场', value: 2 },
        ],
        queryParams: {
            ApplyNo: null, Time: null, Status: null, DepartmentId: null, TypeId: null, FactoryAreaId: 1
        },
        Ids: [],
        BasicList:[],
        imgUrl: "",
        previewShow: false,
        uploadImg: {
            previewVisible: false,
            previewImage: "",
            previewTitle: "",
            fileList: [

            ]
        },


  
  
        popShow: false,
        popType: 0,
        popTitle:"",
        itemRender: (data) => {
            let uid = data.file.uid
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnPreview(uid) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, { default: () => '预览' })
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDownLoad(uid) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, { default: () => '下载' })
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, { default: () => '删除' })


            const FDBtn = h(antd.Popconfirm, {
                title: "确定删除此文件？确定后不可恢复",
                onConfirm: () => methods.btnDelete(data)

            }, { default: () => [deleteBtn] })


            var btns = btns = h('div', { style: "display:flex;margin-left:10px" }, {
                default: () => [
                    isImageFile(data.file.url)? previewBtn:null,
                    downloadBtn,
                    FDBtn,
                ]
            })

            return h('div', { style: 'margin-top:10px; width:100%;align-items:center; display:flex;justify-content:space-between' }, {
                default: () => [
                    data.file.name, btns
                ]
            })

        },


        pagination: {
            total: 0,
            current: 1,
            pageSize: 10,
            loading: true,
            showTotal: total => `总共 ${total} 项`,
            defaultPageSize: 10,
            showSizeChanger: true, // 是否显示pagesize选择
            showQuickJumper: false, // 是否显示跳转窗
        },
        deptList: [

        ],

        GHForm: {
            FormNo: null,
            Time:null
        },
        SHForm: {
            UserNo: null,
            Time: null
        },


        SendForm: {
            EmployeeName: null,
            EmployeeNo: null,
            Quantity: null,
            Remark: null
        },


        FormRule: {
            EmployeeName: { required: true, message: '请填写姓名', trigger: 'change' },
            EmployeeNo: { required: true, message: '请填写工号', trigger: 'change' },
            Quantity: { required: true, message: '请填写数量', trigger: 'change' },
        },




        GHDataSource: [],
        GHColumns: [{
            title: '序号',
            dataIndex: 'no',
            key: 'no',
            align: 'center',
            width: 80,
            customRender: ({ index }) => {
                return index + 1
            },
        },

            {
                title: '申请单号',
                dataIndex: 'FormId',
                key: 'FormId',
                align: 'center',

            },
            {

                title: '领取时间',
                dataIndex: 'UpdateTime',
                key: 'UpdateTime',
                align: 'center',
                customRender: function ({ text }) {

                    return dealTime(text, 'YYYY-MM-DD HH:mm')
                }
            },
            {
                title: '领取数量',
                dataIndex: 'Quantity',
                key: 'Quantity',
                align: 'center',

            },
   
        ],


        SHDataSource: [],
        SHColumns: [{
            title: '序号',
            dataIndex: 'no',
            key: 'no',
            align: 'center',
            width: 80,
            customRender: ({ index }) => {
                return index+1
            },
        },

        {
            title: '领用人',
            dataIndex: 'EmployeeName',
            key: 'EmployeeName',
            align: 'center',
            customRender: function ({ record }) {
                return `${record.EmployeeName}(${record.EmployeeNo})`
                /*  return dealTime(text, 'YYYY-MM-DD')*/
            }
        },
        {

            title: '领取时间',
            dataIndex: 'UpdateTime',
            key: 'UpdateTime',
            align: 'center',
            customRender: function ({ text }) {
   

                return dealTime(text, 'YYYY-MM-DD HH:mm')
            }
        },
        {
            title: '领取数量',
            dataIndex: 'Quantity',
            key: 'Quantity',
            align: 'center',

            },
           {
                title: '附件',
               dataIndex: 'FileList',
               key: 'FileList',
               align: 'center',

               customRender: function ({ text }) {

           

              let bdivs= text.map(e => {
           
                       const dbtn = h(antd.Button, {
                           type: 'link',
                           onClick: () => {
                               downloadfun(e.FileName, e.FilePath)
                           }
                       }, () => '下载');
  

                  return h('div', {
                      
                  }, {
                           default: () => [`${e.FileName}`, dbtn]
                       })

              })

                   return bdivs.length==0?'-':bdivs

             
               }

            },
        ],
      /*  / PPE / GetProvideRecord*/
        columns1: [
            {
                title: '序号',
                dataIndex: 'no',
                key: 'no',
                align: 'center',
                width: 80,
                customRender: ({ index }) => {
                    return (params.pagination.value.current - 1) * params.pagination.value.pageSize + index + 1
                },
            },
            {
                title: '申请部门',
                dataIndex: 'DepartmentName',
                key: 'DepartmentName',
                align: 'center',

            },

            //{
            //    title: '物品类型',
            //    dataIndex: 'type',
            //    key: 'type',
            //    align: 'center',

            //},
            {
                title: '劳防物品',
                dataIndex: 'ProductName',
                key: 'ProductName',
                align: 'center',
                customRender: ({ record }) => {
                    return `${record.ProductName}(${record.AttrName})`
                },
            },
            {

                title: '现有数量',
                dataIndex: 'StorageQuantity',
                key: 'StorageQuantity',
                align: 'center',

            },
            {

                title: '厂区',
                dataIndex: 'FactoryAreaName',
                key: 'FactoryAreaName',
                align: 'center',

            },
            
            {
                title: '操作',
                key: 'action',
                align: 'center',
                customRender: function ({ record }) {

                    let getRecordHistoryBtn = h(antd.Button, {

                        type: "link",

                        onClick: () => {
                            methods.handleGHL(record)
                        }
                    }, { default: () => '领取记录' })



                    let distributeRecordHistoryBtn = h(antd.Button, {

                        type: "link",

                        onClick: () => {
                            methods.handleSH(record)
                        }
                    }, { default: () => '发放记录' })





                    let distributeRecordBtn = h(antd.Button, {

                        type: "link",
                        disabled: record.StorageQuantity == 0,
                        onClick: () => {
                            methods.handleS(record)
                        }
                    }, { default: () => '发放' })

                    let ndistributeRecordBtn= h(antd.Popover, {
                        title: '温馨提示',
                        content: '库存不足',
                    }, () => [distributeRecordBtn]);


         



                    return h('div', {
                    },
                        { default: () => [getRecordHistoryBtn, distributeRecordHistoryBtn, record.StorageQuantity ==0 ? ndistributeRecordBtn: distributeRecordBtn] }
                    );

                }
            },
        ],
        dataSource1: [],
 

        StatusList: [],

    })
    let params = toRefs(data)
    const methods = {
        sChange: (e) => {
            Storage.set('FactoryAreaId', e)
        },
        tchange: () => {

            methods.GetStatusList()
            methods.getTableList(true)

            params.queryParams.value = {

            }
            params.queryParams.value.FactoryAreaId = +Storage.get('FactoryAreaId') || null
            params.Ids.value = []
        },
        GetBasicList: () => {
            Request({
                url: "/PPE/GetBasicList",
                method: 'post',
                data: {
                    TypeId: params.cIndex.value
                }
            }).then(res => {
                params.BasicList.value = res.Data.map(e => {
                    return {
                        label: e.ProductName,
                        value: e.Id
                    }
                })

            })
        },
        setVisible: (value) => {
            params.previewShow.value = value;
        },
        handleSearch1: () => {
            methods.GetPPEReceiveRecordList()
        },
        handleSearch2: () => {
            methods.GetProvideRecordList()
        },

    GetPPEReceiveRecordList: () => {
        params.pagination.value.loading=true
        Request({
            url: "/PPE/GetPPEReceiveRecord",
            method: 'post',
            data: {
                "StartTime": params.GHForm.value.Time && dayjs(params.GHForm.value.Time[0]).format('YYYY-MM-DD'),
                "EndTime": params.GHForm.value.Time && dayjs(params.GHForm.value.Time[1]).format('YYYY-MM-DD'),
                "FormNo": params.GHForm.value.FormNo,
                "Id": params.cid.value
            }
        }).then(res => {
            console.log({
                "StartTime": params.GHForm.value.Time && dayjs(params.GHForm.value.Time[0]).format('YYYY-MM-DD'),
                "EndTime": params.GHForm.value.Time && dayjs(params.GHForm.value.Time[1]).format('YYYY-MM-DD'),
                "FormNo": params.GHForm.value.FormNo,
                "Id": params.cid.value
            }, 'params.GHForm.value')
            params.GHDataSource.value = res.Data.Data

        }).finally(() => {
            params.pagination.value.loading = false
        })
    },


        GetProvideRecordList: () => {
            params.pagination.value.loading = true
            Request({
                url: "/PPE/GetProvideRecord",
                method: 'post',
                data: {
                    "StartTime": params.SHForm.value.Time&& dayjs(params.SHForm.value.Time[0]).format('YYYY-MM-DD'),
                    "EndTime": params.SHForm.value.Time&&dayjs(params.SHForm.value.Time[1]).format('YYYY-MM-DD'),
                    "UserNo": params.SHForm.value.UserNo,
                    "Id": params.cid.value
                }
            }).then(res => {
                params.SHDataSource.value = res.Data.Data

            }).finally(() => {
                params.pagination.value.loading = false
            })
        },





        btnPreview: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            if (item.url.indexOf('.pdf') != -1) {
                params.pdfurl.value = item.url
                params.pdfOpen.value = true
            } else {
                params.imgUrl.value = item.url

                methods.setVisible(true)
            }
        },
        btnDownLoad: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            const { name, url } = item
            params.uploadLock.value = true
            downloadfun(name, url).finally(() => {
                params.uploadLock.value = false

            })

        },
        btnDelete: (e) => {
            const { FileId, uid } = e.file
            if (FileId) {

                IDeletePPEFile(Request, FileId).then(res => {

         
                    params.uploadImg.value.fileList = params.uploadImg.value.fileList.filter(es => es.uid != uid)
                })
            }
        },
  

        GetStatusList: () => {
            Request({
                url: "/PPE/GetStatusList",
                method: 'post',
                data: {
                    TypeId: params.cIndex.value
                }
            }).then(res => {
                params.StatusList.value = res.Data

            })
        },
   

  

        handleChange: (info) => {
    
            if (!params.uploadLock.value) {
                params.uploadLock.value = true

                let formData = new FormData();
                formData.append('nfile', info.file.originFileObj)
                formData.append('uid', info.file.originFileObj.uid)
                Request({
                    url: "/download/uploadfile?Path=PPE/Apply",
                    method: 'post',
                    data: formData
                }).then(res => {
                    params.uploadLock.value = false
                    let item = params.uploadImg.value.fileList.find(e => e.uid == res.Data[0].uid)
                    item.url = imageBaseUrl + res.Data[0].FilePath.split('../..')[1]
                    item.FileId = res.Data[0].FileId
                    item.FileName = res.Data[0].FileName
                    item.name = res.Data[0].FileName
                })
            }

      

        },





        handlePopOk: () => {
            if (params.popType.value == 0) {

            




            } else if (params.popType.value == 1) {


             
            }
            else if (params.popType.value == 2) {


                params.proxy.value.$refs.sFormRule.validate()
                    .then(() => {

                        Request({
                            url: "/PPE/AddPPEProvideRecord",
                            method: 'post',
                            data: {
                                Id: params.cid.value,
                                ...params.SendForm.value,
                                FileList: params.uploadImg.value.fileList.map(e => e.FileId)
                            },
                        }).then(res => {
                            params.SendForm.value = {
                                EmployeeName: null,
                                EmployeeNo: null,
                                Quantity: null,
                                Remark: null
                            },
                                params.uploadImg.value.fileList = []

                            methods.getTableList(true)
                            params.messageTest.value.info(res.Msg);

                        })
                    })
                    .catch(error => {
                        console.log('error', error);
                    });

             
            } 
        },






        handleGHL: (record) => {
            console.log(record,'record')
            params.cid.value = record.Id
            params.popTitle.value = `${record.ProductName}(${record.AttrName})领取记录 | 当前现有数量：${record.StorageQuantity}`
            params.popType.value = 0
            params.popShow.value = true
            methods.GetPPEReceiveRecordList()
        },

        handleSH: (record) => {
            params.popTitle.value = `${record.ProductName}(${record.AttrName})领取记录 | 当前现有数量：${record.StorageQuantity}`
            params.cid.value = record.Id
            params.popType.value = 1
            params.popShow.value = true
            methods.GetProvideRecordList()
        },
        handleS: (record) => {
            params.cid.value = record.Id
            params.popType.value = 2
            params.popShow.value = true

        



        },

        filterOption: (val, type) => {
            return `${type.label}`.includes(`${val || ''}`)
        },



        handleTableChange: (page) => {
            const { current, pageSize } = page
            params.pagination.value.current = current;
            params.pagination.value.pageSize = pageSize;
            methods.getTableList()
        },


        getTableList: async (isRresh) => {
            params.queryParams.value.StartTime = params.queryParams.value.Time && params.queryParams.value.Time[0] && dayjs(params.queryParams.value.Time[0]).format('YYYY-MM-DD HH:mm:ss')
            params.queryParams.value.EndTime = params.queryParams.value.Time && params.queryParams.value.Time[1] && dayjs(params.queryParams.value.Time[1]).format('YYYY-MM-DD HH:mm:ss')
            params.queryParams.value.TypeId = params.cIndex.value

            if (isRresh) {
                params.pagination.value.current = 1
            }
            params.pagination.value.loading = true


            Request({
                url: "/PPE/GetPPEStorageList",
                method: 'post',
                data: params.queryParams.value,
            }).then(res => {

          
                params.dataSource1.value = res.Data.Data
                params.pagination.value.total = res.Data.TotalItemCount
                params.pagination.value.loading = false
                params.popShow.value = false
            })

        },
   



 
        
        GetEuqTypeList: () => {
            return new Promise((resolve, rej) => {
                Request({
                    url: "/PPE/GetEuqTypeList",
                    method: 'post',

                }).then(res => {
                    params.tabList.value =[ res.Data.map(e => {
                        return {
                            label: e.TypeName,
                            value: e.Id
                        }
                    })[0]]
                    let urlParams = queryURLParams()
                    params.cIndex.value = +urlParams.TypeId || +params.tabList.value[0].value
                    methods.tchange()
                    resolve(1)

                }).catch(err => {
                    rej(0)
                })


            })
      
        },
        getDeptList: async () => {
            params.deptList.value = await IgetDeptList(Request)
        },



        init: () => {
              getBrowserInfo().catch(err => { console.log(err)})
            if (proxy) {
                params.proxy.value = proxy
            }

            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });
            params.queryParams.value.FactoryAreaId = +Storage.get('FactoryAreaId') || null

            setTimeout(() => {
                let info = Storage.get('AccountInfo', true)
                Request({
                    url: "/account/createjwttoken",
                    method: 'post',
                    data: {
                        "userName": info && info.UserNo
                    }
                }).then(async (res) => {
                    Storage.set('token', res.Data,true)
                    methods.getDeptList()
                    methods.GetBasicList()
                    methods.GetEuqTypeList().then(res => {
                        methods.GetStatusList()

                    })
          
     

  
                })

            },1000)

    













        },

    }



    const template = {
        pdfPopModel: {
            template: `
           <a-modal v-model:open="pdfOpen" width = "80%" title = "PDF预览" v-on:ok="pdfOpen=false" >
<div style='height:700px'>
                <embed id="pdfviewscreen" :src="pdfurl" type="application/pdf" width="100%" style="height:100%;" />

</div>
  
            </a-modal >
`,
            setup() {
                return {
                    ...params,
                    ...methods,
                };
            }
        },
        test: {
            template: `<div @click="add">+</div> <div>{{testnum}}</div>`,

            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }
    return {
        ...params,
        ...methods,
        template
    }
}

export default Composition